#include <stdio.h>
#include <time.h>
#include <string.h>
#include "global.h"
#include "md5.h"
#include <sys/time.h>
#include <sys/resource.h>
#include <time.h>
#include <math.h>
#include "mddriver.h"

/*
 * chrono: fonction de chronométrage
 * @param timer objet chrono
 * @param mode  CHRONO_START : démarrage du chrono, CHRONO_STOP : arrêt du chrono
 * @author fred
 * return 0 si CHRONO_START, temps passé en secondes depuis CHRONO_START si CHRONO_STOP
 */
long chrono(chronographe *timer, int mode) {
  struct rusage start_time;
  struct rusage stop_time;

  if (mode == CHRONO_START) {
    getrusage(RUSAGE_SELF, &start_time);
    timer->start_utime = start_time.ru_utime.tv_sec;
    timer->start_stime = start_time.ru_stime.tv_sec;
    return 0;
  } else if (mode == CHRONO_STOP) {
    getrusage(RUSAGE_SELF, &stop_time);
    timer->stop_utime = stop_time.ru_utime.tv_sec;
    timer->stop_stime = stop_time.ru_stime.tv_sec;
    return ((timer->stop_utime - timer->start_utime) + 
	    (timer->stop_stime - timer->start_stime));
  }
  return 0;
}

/*int main (argc, argv)
     int argc;
     char *argv[];
{
  int i,charsetNumber[15]={0,0,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
  chunk(5,5,charsetNumber,528900,528910);
  for(i=0;i<10*16;i++)
    printf("%c",*(memPartagee+i));
  printf("\n");

  char *toto = (char*)malloc(5*sizeof(char));
  for (i=0; i<10; i++) {
    memcpy(toto, memPartagee+(i*5), 5);
    //sscanf("");
    printf("-%s-", toto);
    MDString(toto);
  }
  return (0);
}*/

/* Digests a string and prints the result.
 */
void MDString (char *string, unsigned char digest[16])
{
  MD_CTX context;
  unsigned int len = strlen(string); //TDOOOOOOOO

  MDInit (&context);
  MDUpdate (&context, string, len);
  MDFinal (digest, &context);
  //printf ("(\"%s\") = ", string);
  //MDPrint (digest);
}

static void MDStringArray (string)
     unsigned char *string;
{
  MD_CTX context;
  unsigned char digest[16];
  unsigned int len = strlen (string);

  MDInit (&context);
  MDUpdate (&context, string, len);
  MDFinal (digest, &context);
  MDPrint (digest);
}

/*
 * test de 10 000 000 * hash md5
 * @author fred
 */
/*static void MDTestSuite ()
{
  long time_spent = 0;
  int i=0;
  chronographe timer;
  printf ("MD5 test:\n");
  chrono(&timer, CHRONO_START);
  for (i=0; i<10000000; i++)
    MDString ("a");
  time_spent = chrono(&timer, CHRONO_STOP);
  printf("Should be 0cc175b9c0f1b6a831c399e269772661\n");
  printf("Time spent : %ld\n", time_spent);
}*/

/* Digests the standard input and prints the result.
 */
void MDFilter ()
{
  MD_CTX context;
  int len;
  unsigned char buffer[16], digest[16];

  MDInit (&context);
  while (len = fread (buffer, 1, 16, stdin))
    MDUpdate (&context, buffer, len);
  MDFinal (digest, &context);

  MDPrint (digest);
  printf ("\n");
}

/* Prints a message digest in hexadecimal.
 */
void MDPrint (digest)
     unsigned char digest[16];
{

  unsigned int i;

  for (i = 0; i < 16; i++)
    printf ("%02x", digest[i]);
  printf("\n");
}
